package com.sky.service.impl;

import com.sky.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {
    @Value("${upload.path}")
    private String uploadPath;
    @Override
    public String saveFile(MultipartFile file) {
        if (file.isEmpty()){
            return "文件不能为空!";
        }
        try {
            String format = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            File file1 = new File(uploadPath + "/" + format);
            if (!file1.exists())file1.mkdirs();

            // 修复路径遍历漏洞：清理文件名，只保留文件名部分
            String originalFilename = file.getOriginalFilename();
            // 获取文件名（去除路径部分）
            String cleanFilename = originalFilename;
            if (originalFilename != null) {
                // 处理Windows和Unix路径分隔符
                int unixPathIndex = originalFilename.lastIndexOf('/');
                int winPathIndex = originalFilename.lastIndexOf('\\');
                int lastIndex = Math.max(unixPathIndex, winPathIndex);
                if (lastIndex != -1) {
                    cleanFilename = originalFilename.substring(lastIndex + 1);
                }
                // 添加时间戳避免文件名冲突
                cleanFilename = UUID.randomUUID().toString() + "-" + cleanFilename ;
            }

            file.transferTo(new File(file1, cleanFilename));

            return "/files/" + format + "/" + cleanFilename;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
